/**
 * @(#)TaskTimer.java 2018年1月6日
 * Copyright(C) 2018 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.timer;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.service.impl.CacheParamManager;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 定时器入口
 * 
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
@Service
public class TaskTimer {
	public static final Logger LOGGER = LoggerFactory.getLogger(TaskTimer.class);

	@Resource
	private RedisClient<String, String> redisClient;

	@Resource
	private CacheParamManager cacheParamManager;

	@Resource
	private TaskTimerService taskTimerService;

	private String taskFlag = PropertiesUtil.getValue("task_flag", "off");

//	@PostConstruct
	private void init() {
		if ("on".equalsIgnoreCase(taskFlag)) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					long expireTime = 60;
					boolean firstFlag = false;
					while (true) {
						try {
							if(!firstFlag){
								Thread.sleep(30 * 1000);
								firstFlag = true;
							}else{
								Thread.sleep(expireTime * 1000);
							}
							Object refreshTime = cacheParamManager.getParamValue(CacheKey.TASK_TIMER_TIME);
							if (refreshTime != null) {
								expireTime = Long.parseLong(refreshTime.toString());
							}
							if (redisClient.evalSetNx(CacheKey.TASK_TIMER_LOCK, expireTime)) {
								taskTimerService.execute();
							}
						} catch (Exception e) {
							LOGGER.error("TaskTimer", e);
						}
					}
				}
			}).start();
		}
	}
}
